/*
 * Copyright (c) 2020 hebeiyiliuba.com
 * All rights reserved.
 *
 */
package org.jeecg.modules.third.etc.waybillInfo.service;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.jeecg.modules.third.jg.report.freight.information.util.WebUtils;
import org.jeecg.common.util.DateUtils;
import org.jeecg.modules.third.etc.waybillInfo.constant.enums.VehiclePlateColorEnum;
import org.jeecg.modules.third.etc.waybillInfo.dto.VehicleRegisterParamDTO;
import org.jeecg.modules.third.etc.waybillInfo.dto.WaybillEndParamDTO;
import org.jeecg.modules.third.etc.waybillInfo.dto.WaybillStartParamDTO;
import org.jeecg.modules.wlhy.hyvehicle.entity.HyVehicle;
import org.jeecg.modules.wlhy.hyvehicle.service.IHyVehicleService;
import org.jeecg.modules.wlhy.order.service.IHyOrderService;
import org.jeecg.modules.wlhy.shipping.entity.HyShippingNote;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * ETC中交智慧发票服务平台接口
 *
 * @author duanlikao
 * @created 2021/1/28
 */
@Service
public class EtcWaybillInfoService {

    @Value(value="${etc-waybillInfo.domain}")
    private String etcApiDomain;

    private final String API_PATH  = "invoice/api/waybillInfo/";
    /**
     * 用户接入ID
     */
    private final String  API_ACCESSID = "";
    /**
     * 税号
     */
    private final String   TAXPLAYERCODE = "";
    /**
     * 发票抬头名称
     */
    private final String  TITLENAME = "";

    @Resource
    private IHyVehicleService vehicleService;

    @Resource
    private IHyOrderService orderService;

    private static final Logger LOGGER = LoggerFactory.getLogger(EtcWaybillInfoService.class);

    /**
     * 车辆备案
     * @param plateNum
     * @param plateColor
     * @return
     */
    public String vehicleRegister(String plateNum ,String plateColor){

        if(StringUtils.isEmpty(plateNum) || StringUtils.isEmpty(plateColor) ){
            return null;
        }

        VehicleRegisterParamDTO vehicleRegisterParamDTO = new VehicleRegisterParamDTO();
        vehicleRegisterParamDTO.setAccessId(API_ACCESSID);
        vehicleRegisterParamDTO.setPlateNum(plateNum);
        if(!VehiclePlateColorEnum.isValidColorType(plateColor)){
           LOGGER.info("EtcWaybillInfoService vehicleRegister plateColor invalid！");
           return null;
        }
        VehiclePlateColorEnum vehiclePlateColorEnum =  VehiclePlateColorEnum.getVehiclePlateColorEnumByType(plateColor);
        vehicleRegisterParamDTO.setPlateColor( vehiclePlateColorEnum.getCode());
        String url = etcApiDomain+API_PATH+"vehicleRegister";

        String  sendResult = null;
        try {
            sendResult = WebUtils.doPost(url, JSONObject.toJSONString(vehicleRegisterParamDTO), WebUtils.DEFAULT_CHARSET);
//            LOGGER.info("EtcWaybillInfoService vehicleRegister  sendResult:{}",sendResult);
            if(StringUtils.isNotEmpty(sendResult)) {
               return sendResult;
            }
        }catch(IOException e) {
            LOGGER.info("EtcWaybillInfoService vehicleRegister  IOException:{}" ,  e.getMessage());
        }
//        if(StringUtils.isNotEmpty(sendResult)) {
//            ApiResponseDTO result = JSONObject.parseObject(sendResult, ApiResponseDTO.class);
//            if(result.getRcode() == 200){
//                return true;
//            }
//        }
        return null;
    }

    /**
     * 运单开始指令
     *
     * @param shippingNote
     * @return
     */
    public String waybillStart( HyShippingNote shippingNote){
//        LOGGER.info("EtcWaybillInfoService waybillStart shippingNote :{} ",shippingNote);
        if(shippingNote== null  ){
            return null;
        }

        WaybillStartParamDTO waybillStartParamDTO = getWaybillStartParamDTO( shippingNote);
        if (waybillStartParamDTO == null)
            return null;

        String url = etcApiDomain+API_PATH+"waybillStart";
//        LOGGER.info("EtcWaybillInfoService waybillStart  url:{} | jsonObject:{}"
//                ,url, JSONObject.toJSONString(waybillStartParamDTO));
        String  sendResult = null;
        try {
            sendResult = WebUtils.doPost(url, JSONObject.toJSONString(waybillStartParamDTO), WebUtils.DEFAULT_CHARSET);
//            LOGGER.info("EtcWaybillInfoService waybillStart  sendResult:{}",sendResult);
            if(StringUtils.isNotEmpty(sendResult)) {
                return sendResult;
            }
        }catch(IOException e) {
            LOGGER.info("EtcWaybillInfoService waybillStart  IOException:{}" ,  e.getMessage());
        }
        return null;
    }

    private WaybillStartParamDTO getWaybillStartParamDTO( HyShippingNote shippingNote) {
        HyVehicle vehicle = vehicleService.getById(shippingNote.getVehicleId());
//        LOGGER.info("EtcWaybillInfoService waybillStart vehicle :{} ",vehicle);
        if( vehicle == null){
            return null;
        }

//        HyOrder hyOrder = orderService.getById(shippingNote.getOrderId());
//        LOGGER.info("EtcWaybillInfoService waybillStart hyOrder :{} ",hyOrder);
//        if( hyOrder == null){
//            return null;
//        }

        WaybillStartParamDTO waybillStartParamDTO= new WaybillStartParamDTO();
        waybillStartParamDTO.setAccessId(API_ACCESSID);
        waybillStartParamDTO.setWaybillNum(shippingNote.getShippingNoteNumber());
        waybillStartParamDTO.setPlateNum(vehicle.getVehicleNumber());

        if(!VehiclePlateColorEnum.isValidColorType(vehicle.getVehiclePlateColorCode())){
            LOGGER.info("EtcWaybillInfoService vehicleRegister plateColor invalid！");
            return null;
        }
        VehiclePlateColorEnum vehiclePlateColorEnum =  VehiclePlateColorEnum.getVehiclePlateColorEnumByType(vehicle.getVehiclePlateColorCode());
        waybillStartParamDTO.setPlateColor( vehiclePlateColorEnum.getCode());

        waybillStartParamDTO.setStartTime(
                DateUtils.dateTimeToString(shippingNote.getStatusDtReceive() )
        );
        waybillStartParamDTO.setEndTime(
                DateUtils.dateTimeToString( shippingNote.getReceiveDate() )
        );
        waybillStartParamDTO.setPredictEndTime(
                DateUtils.dateTimeToString( shippingNote.getReceiveDate() )
        );
        waybillStartParamDTO.setSourceAddr(shippingNote.getSendAddress());
        waybillStartParamDTO.setDestAddr(shippingNote.getReceiveAddress());

        Integer costPay = shippingNote.getCostPay().intValue() * 100;
        waybillStartParamDTO.setFee(costPay.longValue());

        waybillStartParamDTO.setTaxplayerCode(TAXPLAYERCODE);
        waybillStartParamDTO.setTitleName(TITLENAME);
        return waybillStartParamDTO;
    }

    /**
     * 运单结束指令
     * @param waybillNum
     * @param realDestAddr 运单实际目的地址
     * @param endRealTime 运单实际结束时间
     * @return
     */
    public String waybillEnd(String waybillNum,String realDestAddr,String endRealTime){

//        LOGGER.info("EtcWaybillInfoService waybillEnd waybillNum :{} | realDestAddr:{} | endRealTime:{}"
//                ,waybillNum , realDestAddr,endRealTime);
        if(StringUtils.isEmpty(waybillNum) || StringUtils.isEmpty(realDestAddr)
                || StringUtils.isEmpty(endRealTime) ){
            return null;
        }
        WaybillEndParamDTO waybillEndParamDTO = new WaybillEndParamDTO();
        waybillEndParamDTO.setAccessId(API_ACCESSID);
        waybillEndParamDTO.setWaybillNum(waybillNum);
        waybillEndParamDTO.setRealDestAddr(realDestAddr);
        waybillEndParamDTO.setEndTime(endRealTime);
        waybillEndParamDTO.setEndRealTime(endRealTime);
        String url = etcApiDomain+API_PATH+"waybillEnd";
//        LOGGER.info("EtcWaybillInfoService waybillEnd  url:{} | jsonObject:{}"
//                ,url, JSONObject.toJSONString(waybillEndParamDTO));
        String  sendResult = null;
        try {
            sendResult = WebUtils.doPost(url, JSONObject.toJSONString(waybillEndParamDTO), WebUtils.DEFAULT_CHARSET);
//            LOGGER.info("EtcWaybillInfoService waybillEnd  sendResult:{}",sendResult);
            if(StringUtils.isNotEmpty(sendResult)) {
                return sendResult;
            }
        }catch(IOException e) {
            LOGGER.info("EtcWaybillInfoService waybillEnd  IOException:{}" ,  e.getMessage());
        }
        return null;
    }

    /**
     * 运单发票查询
     * @param waybillNum
     * @return
     */
    public String byWaybillNum(String waybillNum){
//        LOGGER.info("EtcWaybillInfoService byWaybillNum waybillNum :{} " ,waybillNum );
        if(StringUtils.isEmpty(waybillNum)  ){
            return null;
        }
        JSONObject jObject = new JSONObject();
        jObject.put("accessId",API_ACCESSID);
        jObject.put("waybillNum",waybillNum);
        String url = etcApiDomain+API_PATH+"byWaybillNum";
//        LOGGER.info("EtcWaybillInfoService byWaybillNum  url:{} | jsonObject:{}"
//                ,url, jObject.toJSONString());
        String  sendResult = null;
        try {
            sendResult = WebUtils.doPost(url, jObject.toJSONString(), WebUtils.DEFAULT_CHARSET);
//            LOGGER.info("EtcWaybillInfoService byWaybillNum  sendResult:{}",sendResult);
            if(StringUtils.isNotEmpty(sendResult)) {
                return sendResult;
            }
        }catch(IOException e) {
            LOGGER.info("EtcWaybillInfoService byWaybillNum  IOException:{}" ,  e.getMessage());
        }
        return null;
    }
}
